<template>
  <div class="goods-price">
    <el-card class="box-card" shadow="never">
      <!-- 商品信息 -->
      <div class="goods-info" v-if="goodsInfo">
        <div class="goods-header">
          <h2>{{ goodsInfo.goods_name }}</h2>
          <div class="goods-meta">
            <el-tag size="medium" type="info" effect="plain">商品编号：{{ goodsInfo.goods_no }}</el-tag>
            <el-tag size="medium" type="info" effect="plain">品牌：{{ goodsInfo.brand_name }}</el-tag>
            <el-tag size="medium" type="info" effect="plain">分类：{{ goodsInfo.class_name }}</el-tag>
          </div>
        </div>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddSpec">新增规格</el-button>
      </div>

      <!-- 规格列表 -->
      <el-table
        v-loading="loading"
        :data="specList"
        border
        style="width: 100%"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 500
        }"
      >
        <el-table-column prop="spec_no" label="规格编号" width="120"></el-table-column>
        <el-table-column prop="spec_name" label="规格名称" min-width="150"></el-table-column>
        <el-table-column prop="spec_code" label="规格编码" min-width="150"></el-table-column>
        <el-table-column prop="spec_unit_name" label="单位" width="100"></el-table-column>
        <el-table-column prop="spec_aux_unit_name" label="辅助单位" width="100"></el-table-column>
        <el-table-column prop="retail_price" label="零售价" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.retail_price ? Number(scope.row.retail_price).toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="wholesale_price" label="批发价" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.wholesale_price ? Number(scope.row.wholesale_price).toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="market_price" label="市场价" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.market_price ? Number(scope.row.market_price).toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="member_price" label="会员价" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.member_price ? Number(scope.row.member_price).toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEditSpec(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDeleteSpec(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 规格编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="80%"
      :close-on-click-modal="false"
      custom-class="spec-dialog"
      top="5vh"
    >
      <el-form 
        :model="specForm" 
        :rules="rules" 
        ref="specForm" 
        label-width="120px"
        class="spec-form"
      >
        <el-card shadow="never" class="form-card">
          <div slot="header" class="form-header">
            <span>基本信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格编号" prop="spec_no">
                <el-input v-model="specForm.spec_no" placeholder="请输入规格编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格名称" prop="spec_name">
                <el-input v-model="specForm.spec_name" placeholder="请输入规格名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="规格编码" prop="spec_code">
                <el-input v-model="specForm.spec_code" placeholder="请输入规格编码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="spec_unit_name">
                <el-input v-model="specForm.spec_unit_name" placeholder="请输入单位"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="辅助单位" prop="spec_aux_unit_name">
            <el-input v-model="specForm.spec_aux_unit_name" placeholder="请输入辅助单位"></el-input>
          </el-form-item>
        </el-card>

        <el-card shadow="never" class="form-card">
          <div slot="header" class="form-header">
            <span>价格信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="零售价" prop="retail_price">
                <el-input-number 
                  v-model="specForm.retail_price" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  placeholder="请输入零售价"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="批发价" prop="wholesale_price">
                <el-input-number 
                  v-model="specForm.wholesale_price" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  placeholder="请输入批发价"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="市场价" prop="market_price">
                <el-input-number 
                  v-model="specForm.market_price" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  placeholder="请输入市场价"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="会员价" prop="member_price">
                <el-input-number 
                  v-model="specForm.member_price" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  placeholder="请输入会员价"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="自定义价格1" prop="custom_price1">
                <el-input-number 
                  v-model="specForm.custom_price1" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  placeholder="请输入自定义价格1"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="自定义价格2" prop="custom_price2">
                <el-input-number 
                  v-model="specForm.custom_price2" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  placeholder="请输入自定义价格2"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" class="form-card">
          <div slot="header" class="form-header">
            <span>尺寸信息</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="重量(kg)" prop="weight">
                <el-input-number 
                  v-model="specForm.weight" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 100%"
                  controls-position="right"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="长(cm)" prop="length">
                <el-input-number 
                  v-model="specForm.length" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 100%"
                  controls-position="right"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="宽(cm)" prop="width">
                <el-input-number 
                  v-model="specForm.width" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 100%"
                  controls-position="right"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="高(cm)" prop="height">
                <el-input-number 
                  v-model="specForm.height" 
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 100%"
                  controls-position="right"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsSpecs, addGoodsSpec, updateGoodsSpec, deleteGoodsSpec } from '@/api/goods'
import { h } from 'vue'

export default {
  name: 'GoodsPrice',
  data() {
    return {
      // 商品信息
      goodsInfo: null,
      // 规格列表
      specList: [],
      loading: false,
      
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增规格',
      specForm: {
        goods_id: '',
        spec_no: '',
        spec_name: '',
        spec_code: '',
        spec_unit_name: '',
        spec_aux_unit_name: '',
        retail_price: 0,
        wholesale_price: 0,
        market_price: 0,
        member_price: 0,
        custom_price1: 0,
        custom_price2: 0,
        weight: 0,
        length: 0,
        width: 0,
        height: 0
      },
      
      // 表单验证规则
      rules: {
        spec_no: [
          { required: true, message: '请输入规格编号', trigger: 'blur' }
        ],
        spec_name: [
          { required: true, message: '请输入规格名称', trigger: 'blur' }
        ],
        spec_code: [
          { required: true, message: '请输入规格编码', trigger: 'blur' }
        ],
        retail_price: [
          { required: true, message: '请输入零售价', trigger: 'blur' }
        ]
      },
      submitLoading: false
    }
  },
  created() {
    // 获取路由参数
    const { 
      goods_id, 
      goods_name, 
      goods_no,
      brand_id,
      brand_name,
      class_id,
      class_name,
      order_id,
      order_status,
      payment_status,
      payment_method,
      trade_no,
      goods_total,
      total_price,
      delivery_fee,
      create_time
    } = this.$route.query
    console.log('路由参数：', this.$route.query)

    if (goods_id) {
      // 设置商品信息
      this.goodsInfo = {
        goods_id,
        goods_name,
        goods_no,
        brand_id,
        brand_name,
        class_id,
        class_name,
        order_id,
        order_status,
        payment_status,
        payment_method,
        trade_no,
        goods_total,
        total_price,
        delivery_fee,
        create_time
      }
      console.log('商品信息：', this.goodsInfo)

      // 加载规格数据
      this.fetchSpecs()
    }
  },
  methods: {
    // 获取规格列表
    async fetchSpecs() {
      try {
        this.loading = true
        const params = {
          goods_id: this.goodsInfo.goods_id,
          order_id: this.goodsInfo.order_id,
          order_status: this.goodsInfo.order_status,
          payment_status: this.goodsInfo.payment_status
        }
        console.log('请求参数：', params)
        
        const result = await getGoodsSpecs(params)
        console.log('规格列表响应：', result)
        
        if (result && result.data) {
          this.specList = result.data.specs || []
        } else {
          this.specList = []
        }
      } catch (error) {
        console.error('获取规格列表失败：', error)
        this.$message.error(error.message || '获取规格列表失败')
        this.specList = []
      } finally {
        this.loading = false
      }
    },
    // 新增规格
    handleAddSpec() {
      this.dialogTitle = '新增规格'
      this.specForm = {
        goods_id: this.goodsInfo.goods_id,
        spec_no: '',
        spec_name: '',
        spec_code: '',
        spec_unit_name: '',
        spec_aux_unit_name: '',
        retail_price: 0,
        wholesale_price: 0,
        market_price: 0,
        member_price: 0,
        custom_price1: 0,
        custom_price2: 0,
        weight: 0,
        length: 0,
        width: 0,
        height: 0
      }
      this.dialogVisible = true
    },
    // 编辑规格
    handleEditSpec(row) {
      this.dialogTitle = '编辑规格'
      this.specForm = { ...row }
      this.dialogVisible = true
    },
    // 删除规格
    handleDeleteSpec(row) {
      if (!row.spec_id) {
        this.$message.error('规格ID不能为空')
        return
      }

      this.$confirm('', {
        title: '删除确认',
        message: h('div', { class: 'delete-confirm-content' }, [
          h('div', { class: 'delete-icon' }, [
            h('i', { class: 'el-icon-warning', style: 'color: #E6A23C; font-size: 24px;' })
          ]),
          h('div', { class: 'delete-message' }, [
            h('p', { style: 'font-size: 16px; margin-bottom: 10px;' }, '确认删除该规格吗？'),
            h('p', { style: 'color: #909399; font-size: 14px;' }, [
              '规格名称：',
              h('span', { style: 'color: #303133;' }, row.spec_name || '-')
            ]),
            h('p', { style: 'color: #909399; font-size: 14px;' }, [
              '规格编号：',
              h('span', { style: 'color: #303133;' }, row.spec_no || '-')
            ])
          ])
        ]),
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'delete-confirm-dialog',
        confirmButtonClass: 'el-button--danger',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            setTimeout(() => {
              done()
            }, 300)
          } else {
            done()
          }
        }
      }).then(async () => {
        try {
          console.log('删除规格，规格ID:', row.spec_id)
          await deleteGoodsSpec(row.spec_id)
          this.$message({
            type: 'success',
            message: '删除成功',
            duration: 2000
          })
          this.fetchSpecs()
        } catch (error) {
          console.error('删除规格失败：', error)
          if (error.response) {
            console.error('错误响应:', error.response.data)
          }
          this.$message.error(error.message || '删除规格失败')
        }
      }).catch(() => {})
    },
    // 提交表单
    handleSubmit() {
      this.$refs.specForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.specForm.spec_id) {
              console.log('this.this.specForm.spec_id', this.specForm.spec_id,this.specForm)
              // 更新规格
              await updateGoodsSpec(this.specForm.spec_id, this.specForm)
            } else {
              // 新增规格
              await addGoodsSpec(this.specForm)
            }
            this.$message({
              type: 'success',
              message: '保存成功',
              duration: 2000
            })
            this.dialogVisible = false
            this.fetchSpecs()
          } catch (error) {
            console.error('保存规格失败：', error)
            this.$message.error(error.message || '保存规格失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-price {
  .goods-info {
    margin-bottom: 24px;
    
    .goods-header {
      h2 {
        margin: 0 0 16px;
        font-size: 20px;
        font-weight: 500;
        color: #303133;
      }
      
      .goods-meta {
        display: flex;
        gap: 12px;
        
        .el-tag {
          border-radius: 4px;
        }
      }
    }
  }
  
  .toolbar {
    margin-bottom: 16px;
  }

  .price {
    color: #F56C6C;
    font-weight: 500;
  }
}

// 删除确认弹窗样式
:deep(.delete-confirm-dialog) {
  .el-message-box__header {
    padding: 20px 20px 0;
  }
  
  .el-message-box__title {
    font-size: 18px;
    font-weight: 500;
  }
  
  .el-message-box__content {
    padding: 20px;
  }
  
  .delete-confirm-content {
    display: flex;
    align-items: flex-start;
    
    .delete-icon {
      margin-right: 15px;
      padding-top: 3px;
    }
    
    .delete-message {
      flex: 1;
      
      p {
        margin: 0;
        line-height: 1.8;
      }
    }
  }
  
  .el-message-box__btns {
    padding: 10px 20px 20px;
    
    .el-button {
      padding: 10px 20px;
      font-size: 14px;
      
      &--danger {
        background-color: #F56C6C;
        border-color: #F56C6C;
        
        &:hover {
          background-color: #f78989;
          border-color: #f78989;
        }
      }
    }
  }
}

// 规格编辑弹窗样式
:deep(.spec-dialog) {
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #EBEEF5;
    margin: 0;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .spec-form {
    .form-card {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-header {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
      
      .el-card__body {
        padding: 20px;
      }
    }
    
    .el-form-item {
      margin-bottom: 22px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }

      // 输入框样式优化
      .el-input {
        .el-input__inner {
          height: 36px;
          line-height: 36px;
          border-radius: 4px;
          border-color: #DCDFE6;
          transition: all 0.3s;
          
          &:hover {
            border-color: #C0C4CC;
          }
          
          &:focus {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }
        }

        &.is-disabled {
          .el-input__inner {
            background-color: #F5F7FA;
            border-color: #E4E7ED;
            color: #C0C4CC;
          }
        }
      }

      // 数字输入框样式优化
      .el-input-number {
        width: 100%;
        line-height: 36px;
        
        .el-input__inner {
          text-align: left;
          padding: 0 12px;
          height: 36px;
          line-height: 36px;
          font-size: 14px;
          color: #303133;
          background-color: #FFFFFF;
          border: 1px solid #DCDFE6;
          border-radius: 4px;
          transition: all 0.3s;
          
          &:hover {
            border-color: #C0C4CC;
          }
          
          &:focus {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
          }

          &::placeholder {
            color: #C0C4CC;
          }
        }

        &:hover {
          .el-input__inner {
            border-color: #C0C4CC;
          }
        }

        &.is-disabled {
          .el-input__inner {
            background-color: #F5F7FA;
            border-color: #E4E7ED;
            color: #C0C4CC;
            cursor: not-allowed;
          }
        }

        // 数字输入框验证状态
        &.is-error {
          .el-input__inner {
            border-color: #F56C6C;
            
            &:focus {
              box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.1);
            }
          }
        }

        &.is-success {
          .el-input__inner {
            border-color: #67C23A;
            
            &:focus {
              box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.1);
            }
          }
        }
      }

      // 输入框提示文字样式
      .el-input__inner::placeholder {
        color: #C0C4CC;
      }

      // 输入框图标样式
      .el-input__prefix,
      .el-input__suffix {
        color: #C0C4CC;
      }

      // 输入框验证状态样式
      &.is-error {
        .el-input__inner {
          border-color: #F56C6C;
          
          &:focus {
            box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.1);
          }
        }
      }

      &.is-success {
        .el-input__inner {
          border-color: #67C23A;
          
          &:focus {
            box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.1);
          }
        }
      }
    }
  }
  
  .dialog-footer {
    padding: 10px 20px 20px;
    text-align: right;
    
    .el-button {
      padding: 10px 20px;
      font-size: 14px;
      
      &--primary {
        background-color: #409EFF;
        border-color: #409EFF;
        
        &:hover {
          background-color: #66b1ff;
          border-color: #66b1ff;
        }
      }
    }
  }
}
</style>